document.addEventListener('DOMContentLoaded', () => {
  // 获取DOM元素
  const startBtn = document.getElementById('start-recording');
  const stopBtn = document.getElementById('stop-recording');
  const clearBtn = document.getElementById('clear-results');
  const exportBtn = document.getElementById('export-data');
  const urlFilterInput = document.getElementById('url-filter');
  const urlBlacklistInput = document.getElementById('url-blacklist');
  const resultsList = document.getElementById('results-list');
  const detailView = document.getElementById('detail-view');
  const closeDetailBtn = document.getElementById('close-detail');
  const deleteItemDetailBtn = document.getElementById('delete-item-detail');
  const detailUrl = document.getElementById('detail-url');
  const detailRequest = document.getElementById('detail-request');
  const detailResponse = document.getElementById('detail-response');
  
  let currentItemId = null;
  
  // 从存储中加载设置
  chrome.storage.local.get(['urlFilter', 'urlBlacklist'], (result) => {
    if (result.urlFilter) urlFilterInput.value = result.urlFilter;
    if (result.urlBlacklist) urlBlacklistInput.value = result.urlBlacklist;
  });
  
  // 添加实时保存设置的功能
  urlFilterInput.addEventListener('input', saveSettings);
  urlBlacklistInput.addEventListener('input', saveSettings);
  
  // 保存设置函数
  function saveSettings() {
    const urlFilter = urlFilterInput.value.trim();
    const urlBlacklist = urlBlacklistInput.value.trim();
    
    chrome.storage.local.set({ urlFilter, urlBlacklist });
    chrome.runtime.sendMessage({ 
      type: 'updateSettings', 
      urlFilter, 
      urlBlacklist 
    });
  }
  
  // 添加按钮事件
  startBtn.addEventListener('click', () => {
    // 先保存最新设置
    saveSettings();
    
    // 再开始录制
    chrome.runtime.sendMessage({ 
      type: 'startRecording',
      urlFilter: urlFilterInput.value.trim(),
      urlBlacklist: urlBlacklistInput.value.trim()
    }, (response) => {
      if (response && response.success) {
        startBtn.disabled = true;
        stopBtn.disabled = false;
      }
    });
  });
  
  // 修复停止按钮监听器
  stopBtn.addEventListener('click', () => {
    chrome.runtime.sendMessage({ type: 'stopRecording' }, (response) => {
      if (response && response.success) {
        startBtn.disabled = false;
        stopBtn.disabled = true;
      }
    });
  });
  
  // 添加清空按钮事件 - 增加确认对话框
  clearBtn.addEventListener('click', () => {
    // 添加二次确认对话框
    if (confirm('确定要清空所有录制的请求数据吗？此操作不可撤销。')) {
      clearResults();
    }
  });
  
  // 增加导出按钮事件监听
  exportBtn.addEventListener('click', exportData);
  
  closeDetailBtn.addEventListener('click', () => {
    detailView.classList.add('hidden');
    currentItemId = null;
  });
  
  deleteItemDetailBtn.addEventListener('click', () => {
    if (currentItemId) {
      deleteRecord(currentItemId, () => {
        detailView.classList.add('hidden');
        currentItemId = null;
      });
    }
  });
  
  // 获取当前录制状态
  chrome.runtime.sendMessage({ type: 'getRecordingState' }, (response) => {
    if (response) {
      startBtn.disabled = response.isRecording;
      stopBtn.disabled = !response.isRecording;
      displayResults(response.data);
    }
  });
  
  // 清空结果
  function clearResults() {
    chrome.runtime.sendMessage({ type: 'clearRecords' }, (response) => {
      if (response && response.success) {
        displayResults([]);
      }
    });
  }
  
  // 显示结果列表
  function displayResults(data) {
    resultsList.innerHTML = '';
    
    // 添加请求总数显示
    document.getElementById('results-count').textContent = `共 ${data.length} 个请求`;
    
    if (data.length === 0) {
      resultsList.innerHTML = '<div class="no-records">尚无录制数据</div>';
      return;
    }
    
    // 按时间排序（最新的在前面）
    data.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    
    data.forEach(item => {
      const resultItem = document.createElement('div');
      resultItem.className = 'result-item';
      resultItem.dataset.id = item.id;
      
      // 修改这里：删除按钮放在最左边
      const actions = document.createElement('div');
      actions.className = 'actions';
      
      const deleteBtn = document.createElement('button');
      deleteBtn.className = 'delete-btn';
      deleteBtn.innerHTML = '&#x2715;'; // X symbol
      deleteBtn.title = '删除此条记录';
      deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        deleteRecord(item.id);
      });
      
      // 添加删除按钮作为第一个元素
      actions.appendChild(deleteBtn);
      resultItem.appendChild(actions);
      
      const method = document.createElement('span');
      method.className = 'method';
      method.textContent = item.method;
      
      const url = document.createElement('span');
      url.className = 'url';
      url.textContent = item.fullUrl || item.url;
      url.title = item.fullUrl || item.url;
      
      const time = document.createElement('span');
      time.className = 'time';
      const date = new Date(item.timestamp);
      time.textContent = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
      
      resultItem.appendChild(method);
      resultItem.appendChild(url);
      resultItem.appendChild(time);
      
      resultItem.addEventListener('click', () => {
        showDetailView(item);
      });
      
      resultsList.appendChild(resultItem);
    });
  }
  
  // 删除记录
  function deleteRecord(id, callback) {
    chrome.runtime.sendMessage({ type: 'deleteRecord', id }, (response) => {
      if (response && response.success) {
        displayResults(response.data);
        if (callback) callback();
      }
    });
  }
  
  // 显示详情视图
  function showDetailView(item) {
    currentItemId = item.id;
    
    detailUrl.textContent = item.fullUrl || item.url; // 显示完整URL
    detailRequest.textContent = item.requestBody || '无请求数据';
    detailResponse.textContent = item.responseBody || '等待响应...';
    
    detailView.classList.remove('hidden');
    
    // 如果响应体为"等待响应..."，启动自动刷新机制
    if (item.responseBody === '等待响应...' || !item.responseBody) {
      checkResponseUpdate(item.id);
    }
  }
  
  // 检查响应更新
  function checkResponseUpdate(id) {
    let checkCount = 0;
    const maxChecks = 30; // 最多检查30次，每次间隔0.5秒，共15秒
    
    const checkInterval = setInterval(() => {
      if (checkCount++ > maxChecks || !currentItemId || currentItemId !== id) {
        clearInterval(checkInterval);
        return;
      }
      
      chrome.runtime.sendMessage({ type: 'getItemById', id }, (response) => {
        if (response && response.item) {
          const item = response.item;
          
          // 只在响应体有更新或不再是"等待响应..."时更新界面
          if (item.responseBody && item.responseBody !== '等待响应...') {
            detailResponse.textContent = item.responseBody;
            clearInterval(checkInterval);
          }
        }
      });
    }, 500);
  }
  
  // 辅助函数：尝试将字符串解析为JSON对象
  function parseJsonIfPossible(str) {
    if (!str) return {};
    
    try {
      // 如果字符串已经是格式化的JSON字符串，则解析回对象
      // 这样可以确保输出的是纯JSON而不是字符串形式
      return JSON.parse(str);
    } catch (e) {
      // 如果无法解析为JSON，尝试去除格式化的空格和换行符
      try {
        // 有时候字符串可能包含格式化的JSON换行符和空格，尝试去除它们
        return JSON.parse(str.replace(/\n\s*/g, ''));
      } catch (e2) {
        // 实在不能解析为JSON，返回空对象
        return {};
      }
    }
  }
  
  // 导出数据函数
  function exportData() {
    chrome.runtime.sendMessage({ type: 'getRecordingState' }, (response) => {
      if (!response || !response.data || response.data.length === 0) {
        alert('没有可导出的数据');
        return;
      }
      
      // 创建简化的导出数据
      const exportData = response.data.map(item => {
        // 只保留需要的三个字段
        return {
          url: item.url, // 只保留接口路径，不要完整URL
          requestBody: parseJsonIfPossible(item.requestBody),
          responseBody: parseJsonIfPossible(item.responseBody)
        };
      });
      
      // 转换为JSON字符串并下载
      const jsonString = JSON.stringify(exportData, null, 2);
      const blob = new Blob([jsonString], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '');
      
      chrome.downloads.download({
        url: url,
        filename: `api_records_${timestamp}.json`,
        saveAs: true
      });
    });
  }
  
  // 监听更新消息
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'updateResults') {
      displayResults(message.data);
    }
    return true;
  });
}); 